﻿using System.Data.Linq;

namespace PropertyExpression.ReactiveRelation.Supplementary
{
    public static class ValueExtensions
    {
        public static IValue<bool> IsDefault<T>(this IValue<T> value)
        {
            return value.Func(arg => default(T).Equals(arg));
        }

        public static IValue<T> GetValueOrDefault<T>(
            this IValue<T?> value1) where T : struct
        {
            return value1.Func(arg => arg.GetValueOrDefault());
        }

        public static IValue<int> Count<TDataSetEntity>(
            this IPropertyValue<EntitySet<TDataSetEntity>> propertyValue)
            where TDataSetEntity : class
        {
            return propertyValue.Aggregate(
                entityWrapper =>
                    {
                        const object obj = null;
                        return obj.Const();
                    },
                () => new CountAggregator()
                );
        }

        private class CountAggregator : IAggregator<object, int>
        {
            public void Process(object arg)
            {
                Result++;
            }

            public int Result { get; private set; }
        }
    }
}
